const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();
const { testConnection } = require('./config/db');
const mqtt = require('mqtt');

// 导入路由
const environmentRoutes = require('./routes/environmentRoutes');
const deviceRoutes = require('./routes/deviceRoutes');
const userRoutes = require('./routes/userRoutes');
const sceneRoutes = require('./routes/sceneRoutes');
const familyRoutes = require('./routes/familyRoutes');
const auditLogRoutes = require('./routes/auditLogRoutes');

const app = express();
const PORT = process.env.PORT || 3000;

// MQTT配置
const mqttConfig = {
  host: 'crychic.link',
  port: 1883,
  clientId: 'environmental_regulation_server_' + Math.random().toString(16).substring(2, 10),
  username: 'mqtt',
  password: 'mqtt',
  clean: true,
  connectTimeout: 4000,
  reconnectPeriod: 1000
};

// 创建MQTT客户端
const mqttClient = mqtt.connect(`mqtt://${mqttConfig.host}:${mqttConfig.port}`, mqttConfig);

// MQTT连接事件处理
mqttClient.on('connect', () => {
  console.log('MQTT服务器连接成功');
  
  // 订阅设备状态主题
  mqttClient.subscribe('device/+/status', (err) => {
    if (!err) {
      console.log('已订阅设备状态主题');
    }
  });
});

mqttClient.on('error', (error) => {
  console.error('MQTT连接错误:', error);
});

mqttClient.on('message', (topic, message) => {
  console.log(`收到来自主题 ${topic} 的消息: ${message.toString()}`);
  // 这里可以处理接收到的消息
});

// 导出MQTT客户端，供其他模块使用
app.locals.mqttClient = mqttClient;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 测试数据库连接
testConnection();

// 路由
app.use('/api/environment', environmentRoutes);
app.use('/api/devices', deviceRoutes);
app.use('/api/users', userRoutes);
app.use('/api/scenes', sceneRoutes);
app.use('/api/families', familyRoutes);
app.use('/api/audit', auditLogRoutes);

// 根路由
app.get('/', (req, res) => {
  res.json({ message: '智能环境舒适调节系统API服务' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

// 优雅关闭
process.on('SIGINT', () => {
  mqttClient.end();
  console.log('已断开MQTT连接');
  process.exit();
});